package com.glasses.orm.spring;

import com.alibaba.fastjson.JSONObject;
import com.glasses.orm.base.BaseController;
import com.glasses.orm.utils.HttpUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * 请求AOP拦截
 * Created by 汪超 on 2017/9/28.
 */
@Component
@Aspect
public class DispatcherServletAop extends BaseController implements Ordered {

    @Pointcut("execution(* *.*.controller.*.*(..)) || execution(* *.*.*.controller.*.*(..)) || target(com.glasses.orm.base.Ex.BaseControllerEx)")
    public void doInit() {
    }


    @Around("doInit()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //獲得Request對象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        Signature sig = joinPoint.getSignature();
        MethodSignature msig;
        long sTime = new Date().getTime();
        if (!(sig instanceof MethodSignature)) {
            throw new IllegalArgumentException("该注解只能用于方法");
        }
        msig = (MethodSignature) sig;
        Method currentMethod = msig.getMethod();
        //訪問完整目標方法路径
        String fullTargetPath = getFullTargetPath(joinPoint);
        //获得方法名
        String targetCls = sig.getName();
        Object o;
        o = joinPoint.proceed();
        if (o instanceof JSONObject) {
            HttpUtils.outJson(o.toString());
            return null;
        } else {
            return o;
        }
    }

    /**
     * 优先级为最后
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 999;
    }

    /**
     * 获得完整的目标路径
     *
     * @param joinPoint 切点
     * @return
     */
    public static String getFullTargetPath(ProceedingJoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method targetMethod = methodSignature.getMethod();
        return targetMethod.getDeclaringClass().getName() + "." + targetMethod.getName();
    }
}
